package com.zpf.controller;

import com.zpf.pojo.Cart;
import com.zpf.pojo.User;
import com.zpf.service.CartService;
import com.zpf.service.impl.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/cart")
public class CartController extends BaseServlet{
        CartService cartService = new CartServiceImpl();
        //删除
    public String delete(HttpServletRequest request,HttpServletResponse response){
        //1.获取当前用户id
        User user = (User) request.getSession().getAttribute("loginUser") ;
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String cid = request.getParameter("cid");

        cartService.deleteById(Integer.parseInt(cid));
        return "redirect:/cart?method=show";
    }




//购物车的商品的增减
     public String update(HttpServletRequest request,HttpServletResponse response){
         //1.获取当前用户id
         User user = (User) request.getSession().getAttribute("loginUser") ;
         if (user == null) {
             return "redirect:/login.jsp";
         }
         String cid = request.getParameter("cid");
         String cnum = request.getParameter("cnum");

         cartService.updateCart(Integer.parseInt(cid),Integer.parseInt(cnum));

         return "redirect:/cart?method=show";
     }

    //创建购物车
    public String create(HttpServletRequest request, HttpServletResponse response){

        //1.获取商品id
        String pid = request.getParameter("pid");

        //2.获取当前用户id
        User user = (User) request.getSession().getAttribute("loginUser");
        if (user == null) {
            return "redirect:/login,jsp";
        }
        //3.调用service业务层，将购物车存入数据库中
        cartService.createCart(user.getId(), Integer.parseInt(pid));
        return "redirect:/cart?method=show";
        //跳转到购物车查询列表方法
    }
    //查询指定用户的购物车数据
    public String show(HttpServletRequest request, HttpServletResponse response){
        //1.获取当前用户id
        User user = (User) request.getSession().getAttribute("loginUser") ;
        //2.根据用户id调用service，查询这个用户购物车数据
        List<Cart> cartList = cartService.findCartListByUid(user.getId());
        //3.将用户的购物车数据放入request请求域中，在页面展示
        request.setAttribute("list",cartList);
        //4.查询

        return "forward:/cart.jsp";
    }
}
